#pragma once

#include <iostream>
#include <string>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <strings.h>
#include <errno.h>
#include <cstring>
#include "Log.hpp"
#include "LockGuard.hpp"
#include "InetAddr.hpp"
#include <functional>

const static int gdefaultfd = -1;

enum
{
    SOCK_ERROR = 1,
    BIND_ERROR,
    USAGE_ERROR
};

using func_t = std::function<std::string(const std::string &, bool &)>;

class UdpServer
{
public:
    UdpServer(uint16_t port, func_t func)
        : _sockfd(gdefaultfd), _port(port), _isrunning(false), _func(func)
    {
    }
    void InitServer()
    {
        // 1. 创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "socket error, %s, %d\n", strerror(errno), errno);
            exit(SOCK_ERROR);
        }
        LOG(DEBUG, "create socket success, sockfd:%d\n", _sockfd);

        // 2. 填充struct sockaddr_in
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        // local.sin_addr.s_addr = inet_addr(_ip.c_str());
        local.sin_addr.s_addr = INADDR_ANY;

        // 3. bind
        int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(FATAL, "bind error, %s, %d\n", strerror(errno), errno);
            exit(BIND_ERROR);
        }
        LOG(DEBUG, "bind success\n");
    }
    void Start()
    {
        // 开始启动服务器
        _isrunning = true;
        while (true)
        {
            char request[1024];
            // 接收客户端发送的信息
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, request, sizeof(request) - 1, 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                request[n] = 0;
                InetAddr addr(peer);
                LOG(DEBUG, "get a message from[%s:%d]: %s\n", addr.Ip().c_str(), addr.Port(), request);
                // 回显回去
                bool ok;
                const std::string respose = _func(request, ok);
                // void(ok);
                sendto(_sockfd, respose.c_str(), respose.size(), 0, (struct sockaddr *)&peer, len);
            }
        }
        _isrunning = false;
    }
    ~UdpServer()
    {
    }

private:
    int _sockfd;
    // std::string _ip;    //不是必须的TODO
    uint16_t _port;
    bool _isrunning;
    func_t _func;
};
